package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryServce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class CategoryServiceImpl implements CategoryServce {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Override
    public Page<Category> findPage(Integer page, Integer pageSize) {
        //设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        //查询数据出来
        List<Category> categoryList=categoryMapper.findPage(page,pageSize);
        //把集合封装到pageinfo对昂
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        //把pageinfo的数据封装到对象中
        Page<Category> categoryPage = new Page<Category>(pageInfo.getList(), pageInfo.getTotal(), page, pageSize);

        return categoryPage;
    }

    @Override
    public void save(Category category) {

        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.save(category);
    }

    @Override
    public void delete(Long id) {
        //1.查询菜品分类中是否有其他的菜
        Long count = dishMapper.findById(id);
        if(count>0){
            throw new CustomException("该分类存在菜品,无法删除");
        }
        long count1=setmealMapper.findById(id);
        if(count1>0){
            throw new CustomException("该套餐存在菜品,无法删除");
        }
        categoryMapper.delete(id);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    @Override
    public List<Category> findByType(Integer type) {
        List<Category> categoryList=categoryMapper.findByType(type);
        return categoryList;
    }
}
